/*
    Dominate 3D - A cube-based game of life

    Copyright (C) 2007, Craig H. Miller (kidmosey@gmail.com)

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __SHAREDOBJECT_H__
#define __SHAREDOBJECT_H__

#include <windows.h>
#include <memory>

template<class T>
class SharedObject
{
public:
    SharedObject(T &obj)
    : m_obj(new T(obj))
    {
        InitializeCriticalSection(&m_criticalSection);
    }

    SharedObject(T *obj = new T)
    : m_obj(obj)
    {
        assert(obj);

        InitializeCriticalSection(&m_criticalSection);
    }

    ~SharedObject()
    {
        DeleteCriticalSection(&m_criticalSection);
    }

    void Reset(T *new_obj)
    {
        DeleteCriticalSection(&m_criticalSection);
        InitializeCriticalSection(&m_criticalSection);

        Lock();
        m_obj.reset(new_obj);
        Unlock();
    }

    T &Lock()
    {
        EnterCriticalSection(&m_criticalSection);
        return *m_obj.get();
    }

    void Unlock()
    {
        LeaveCriticalSection(&m_criticalSection);
    }

private:
    CRITICAL_SECTION m_criticalSection;
    std::auto_ptr<T> m_obj;
};

#endif // __SHAREDOBJECT_H__
